﻿using System;
using System.Collections.Generic;
using System.Reflection;
using YawetagLib.Services;
using YawetagLib.Utilities;

namespace YawetagLib.Facade
{
    public abstract class BaseFacadeFactory : IFacadeFactory
    {
        private readonly object _lock = new object();

        protected BaseFacadeFactory()
        {
            ServiceBroker = new ServiceBroker();
            Instances = new Dictionary<Type, IFacade>();
        }

        public void RegisterService<TService>() where TService : class, IService
        {
            ServiceBroker.RegisterService<TService>();
        }

        public void RegisterServices(Assembly assembly)
        {
            ServiceBroker.RegisterServices(assembly);
        }

        public void UnRegisterService<TService>() where TService : class, IService
        {
            ServiceBroker.UnRegisterService<TService>();
        }

        public void UnRegisterServices(Assembly assembly)
        {
            ServiceBroker.UnRegisterServices(assembly);
        }

        public TFacade Get<TFacade>() where TFacade : IFacade
        {
            Type facadeType = TypeResolver.Get(typeof(TFacade));

            lock (_lock)
            {
                if (!Instances.ContainsKey(facadeType))
                {
                    Instances.Add(typeof(TFacade), GetFacadeInstance(facadeType));
                }
            }

            return (TFacade)Instances[facadeType];
        }

        protected virtual BaseFacade GetFacadeInstance(Type facadeType)
        {
            return (BaseFacade)Activator.CreateInstance(facadeType, this, ServiceBroker);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!IsDisposed)
            {
                if (disposing)
                {
                    ManagedResourceCleanup();
                }
                UnmanagedResourceCleanup();
                IsDisposed = true;
            }
        }

        protected virtual void ManagedResourceCleanup()
        {
            ServiceBroker.Dispose();
        }

        protected virtual void UnmanagedResourceCleanup()
        {
        }

        ~BaseFacadeFactory()
        {
            Dispose(false);
        }

        public ServiceBroker ServiceBroker { get; private set; }

        protected IDictionary<Type, IFacade> Instances { get; private set; }

        private bool IsDisposed { get; set; }
    }
}
